from microphone import Microphone
from asr import Transcriber
from tokenizer import get_intent_from_text
import socket
import json

MODEL_DIR = "/home/bcsh/Documents/Models/transcribe"
SAMPLE_RATE = 16000

import signal
import sys

# Ctrl+C 触发关闭程序
def sigint_handler(signum, frame):
    print("Ctrl-C pressed, exiting gracefully...")
    sys.exit(0)

signal.signal(signal.SIGINT, sigint_handler)


def send_data_to_server(server_ip, server_port, mic, ts):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    with mic.start_stream() as mic_stream:
        try:
            while True:
                samples = mic_stream.read()
                user_input, is_endpoint = ts.transcribe(samples)

                if not user_input or not is_endpoint:
                    continue

                if is_endpoint and len(user_input) > 0:
                    print(f"用户输入语音为:{user_input}")

                if user_input == 'q':
                    print("用户退出")
                    break

                intents_data = get_intent_from_text(user_input)
                if len(intents_data) == 0:
                    print("无法识别指令，请重新输入。")
                    ts.reset()
                    continue

                json_data = json.dumps(intents_data[0], indent=4, ensure_ascii=False)
                print("\n转换为 JSON 并发送到机械臂:\n")
                print(json_data)
                try:
                    s.sendto(json_data.encode(), (server_ip, server_port))
                    ts.reset()
                except Exception as e:
                    print(f"发送数据时出错: {e}")
                    break
        finally:
            s.close()
            
            
if __name__ == "__main__":

    test_strings = {
        1: '移动到1号位置',
        2: '移动到2号位置',
        3: '抓取1号位置的物品',
        4: '放下物品到4号位置',
        5: '放到5号位置',
        6: '去11号位置'
    }

    server_ip = "localhost" 
    server_port = 12345  

    mic = Microphone()
    device_id = ""
    mic.select_device(device_id)
    ts = Transcriber(model_dir=MODEL_DIR, sample_rate=SAMPLE_RATE)

    send_data_to_server(server_ip, server_port, mic, ts)
